/**
 * VimL AST解析示例
 * 
 * 本示例展示了VimL虚拟机的词法分析和语法解析过程，包括：
 * 1. 源代码的词法分析（Token化）
 * 2. Token序列的语法解析（AST生成）
 * 3. AST节点结构的检查
 * 
 * 编译和运行：
 * mkdir -p build && cd build
 * cmake .. && ninja
 * ./bin/ast_parsing_example
 * 
 * 作者：VimL虚拟机项目组
 * 日期：2025-09-27
 */

#include "viml/lexer.h"
#include "viml/parser.h"
#include "viml/ast.h"
#include <iostream>
#include <typeinfo>

using namespace viml;

void print_header(const std::string& title) {
    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(50, '=') << std::endl;
}

std::string get_token_type_name(TokenType type) {
    switch(type) {
        case TokenType::LET: return "LET";
        case TokenType::FUNCTION: return "FUNCTION";
        case TokenType::ENDFUNCTION: return "ENDFUNCTION";
        case TokenType::RETURN: return "RETURN";
        case TokenType::ECHO: return "ECHO";
        case TokenType::IDENTIFIER: return "IDENTIFIER";
        case TokenType::NUMBER: return "NUMBER";
        case TokenType::STRING: return "STRING";
        case TokenType::ASSIGN: return "ASSIGN";
        case TokenType::PLUS: return "PLUS";
        case TokenType::LPAREN: return "LPAREN";
        case TokenType::RPAREN: return "RPAREN";
        case TokenType::COMMA: return "COMMA";
        case TokenType::NEWLINE: return "NEWLINE";
        case TokenType::END_OF_FILE: return "EOF";
        default: return "UNKNOWN";
    }
}

std::string simplify_type_name(const std::string& mangled_name) {
    if (mangled_name.find("LetStatement") != std::string::npos) return "LetStatement";
    if (mangled_name.find("FunctionStatement") != std::string::npos) return "FunctionStatement";
    if (mangled_name.find("CallExpression") != std::string::npos) return "CallExpression";
    if (mangled_name.find("Identifier") != std::string::npos) return "Identifier";
    if (mangled_name.find("NumberLiteral") != std::string::npos) return "NumberLiteral";
    return mangled_name;
}

int main() {
    try {
        print_header("VimL AST解析演示");
        
        std::string source = R"(
function add_numbers(a, b)
    let result = a + b
    return result
endfunction

let sum = add_numbers(10, 20)
echo sum
)";
        
        std::cout << "源代码：" << std::endl;
        std::cout << source << std::endl;
        
        // 词法分析
        print_header("词法分析");
        Lexer lexer(source);
        auto tokens = lexer.tokenize();
        
        std::cout << "Token数量: " << tokens.size() << std::endl;
        int count = 0;
        for (const auto& token : tokens) {
            if (token.type == TokenType::NEWLINE) continue;
            std::cout << count++ << ": " << get_token_type_name(token.type) 
                     << " [" << token.value << "]" << std::endl;
            if (count > 15) {
                std::cout << "... (省略其余Token)" << std::endl;
                break;
            }
        }
        
        // 语法分析
        print_header("语法分析");
        Parser parser(tokens);
        auto program = parser.parse();
        
        std::cout << "AST解析成功！" << std::endl;
        std::cout << "顶层语句数: " << program->statements.size() << std::endl;
        
        for (size_t i = 0; i < program->statements.size(); ++i) {
            auto stmt = program->statements[i].get();
            std::string type_name = simplify_type_name(typeid(*stmt).name());
            std::cout << "语句 " << i + 1 << ": " << type_name << std::endl;
            
            if (auto func_stmt = dynamic_cast<FunctionStatement*>(stmt)) {
                std::cout << "  函数名: " << func_stmt->name << std::endl;
                std::cout << "  参数数量: " << func_stmt->parameters.size() << std::endl;
            }
            
            if (auto let_stmt = dynamic_cast<LetStatement*>(stmt)) {
                std::cout << "  变量名: " << let_stmt->name << std::endl;
                if (auto call_expr = dynamic_cast<CallExpression*>(let_stmt->value.get())) {
                    if (auto ident = dynamic_cast<Identifier*>(call_expr->callee.get())) {
                        std::cout << "  调用函数: " << ident->name << std::endl;
                    }
                }
            }
        }
        
        print_header("AST解析完成");
        std::cout << "✓ 词法分析器正常工作" << std::endl;
        std::cout << "✓ 语法解析器正常工作" << std::endl;
        std::cout << "✓ AST结构正确生成" << std::endl;
        std::cout << "\n🎉 AST解析功能验证完成！" << std::endl;
        
    } catch (const std::exception& e) {
        std::cout << "\n❌ AST解析演示失败: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}